package com.choudou5.solr.web.handler.sys;

import com.choudou5.solr.annotation.ReqMapping;
import com.choudou5.solr.annotation.ReqMethod;
import com.choudou5.solr.api.IndexApi;
import com.choudou5.solr.api.SearchApi;
import com.choudou5.solr.bean.SolrElevateBean;
import com.choudou5.solr.bean.common.*;
import com.choudou5.solr.core.util.SolrHelper;
import com.choudou5.solr.framework.constants.ErrorResp;
import com.choudou5.solr.framework.constants.SolrModuleEnum;
import com.choudou5.solr.framework.util.PageJumpUtil;
import com.choudou5.solr.framework.util.RequestUtil;
import com.choudou5.solr.searchrule.SolrQueryRuleService;
import com.choudou5.solr.service.ServiceHelper;
import com.choudou5.solr.service.SolrElevateService;
import com.choudou5.solr.util.StrUtil;
import com.choudou5.solr.utils.QueryBuilder;
import com.choudou5.solr.utils.SolrQueryBuilder;
import com.choudou5.solr.utils.SqlQueryBuilder;
import com.choudou5.solr.web.handler.BaseHandler;
import com.choudou5.spider.service.SpiderService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Name：搜索优化器
 * @Author：choudou5
 * @Date：2018-07-14
 */
public class SearchOptimizeHandler extends BaseHandler {

    private final SearchApi searchApi = SearchApi.getInstance();
    private final IndexApi indexApi = IndexApi.getInstance();

    private final SolrElevateService solrElevateService = ServiceHelper.singleton(SolrElevateService.class);


    @Override
    public void execute(String bizMethod, HttpServletRequest req, HttpServletResponse resp) {
        logger.info("SearchOptimizeHandler bizMethod:{}", bizMethod);
        switch (bizMethod){
            case "pageList":
                pageList(req, resp);
                break;
            case "search":
                search(req, resp);
                break;
            case "addElevate":
                addElevate(req, resp);
                break;
            case "elevateList":
                elevateList(req, resp);
                break;
            case "getSpiderData":
                getSpiderData(req, resp);
                break;
            case "adoptQASpiderData":
                adoptQASpiderData(req, resp);
                break;
            default:
                PageJumpUtil.errorOut(ErrorResp.Not_Found, req, resp);
                break;
        }
    }

    /**
     * 分页列表
     * @param req
     * @param resp
     */
    private void pageList(HttpServletRequest req, HttpServletResponse resp){
        String module = RequestUtil.getStrParameter(req, "module", "qa");
        if(!SolrHelper.existCoreName(module)){
            PageJumpUtil.errorOut(ErrorResp.INVALID_PARAM, "无效的搜索模块", req, resp);
            return;
        }
        PageJumpUtil.forward("example/" + StrUtil.toJavaVariableName(module) + "List", req, resp);
    }


    /**
     * 搜索
     * @param req
     * @param resp
     */
    private void search(HttpServletRequest req, HttpServletResponse resp){
        String keyword = RequestUtil.getStrParameter(req, "keyword");
        String module = RequestUtil.getStrParameter(req, "module", SolrModuleEnum.getDefKey());
        if(!SolrHelper.existCoreName(module)){
            PageJumpUtil.errorOut(ErrorResp.INVALID_PARAM, "无效的搜索模块", req, resp);
            return;
        }
        PageBean pageBean = QueryBuilder.buildPageBean(req);
        SolrQueryParam query = SolrQueryRuleService.getQueryRule(module, keyword, pageBean);
        SolrQueryBuilder.appendFilterQuery(req, query);//追加过滤条件
        DataTableBean pageResult = searchApi.search(query);
        pageResult.setDraw(RequestUtil.getIntParameter(req, "draw", 1));
        PageJumpUtil.writeObjToJson(pageResult, resp);
    }


    @ReqMapping(desc = "新增竞价排名", method = ReqMethod.POST)
    private void addElevate(HttpServletRequest req, HttpServletResponse resp){
        String keyword = RequestUtil.getStrParameter(req, "keyword");
        String module = RequestUtil.getStrParameter(req, "module", SolrModuleEnum.getDefKey());
        if(!SolrHelper.existCoreName(module)){
            PageJumpUtil.errorOut(ErrorResp.INVALID_PARAM, "无效的搜索模块", req, resp);
            return;
        }
        Map<String, String> map = RequestUtil.getMapRequest(req, "params");
        if(map.isEmpty()){
            PageJumpUtil.errorOut(ErrorResp.INVALID_PARAM, "请选择提升排名项", req, resp);
            return;
        }
        solrElevateService.save(module, keyword, map);
        PageJumpUtil.writeJsonOk("添加成功, 请再次查询查看优化结果", resp);
    }

    /**
     * 竞价排名列表
     * @param req
     * @param resp
     */
    private void elevateList(HttpServletRequest req, HttpServletResponse resp){
        SqlQueryBean sqlQueryBean = SqlQueryBuilder.buildWhereSql(req);
        sqlQueryBean.setOrderDefParam("update_time", "desc");
        PageResult<SolrElevateBean> pageResult = solrElevateService.findPage(sqlQueryBean);
        req.setAttribute("pageResult", pageResult);
        PageJumpUtil.forward("elevateList", req, resp);
    }


    /**
     * 获取爬虫数据
     * @param req
     * @param resp
     */
    private void getSpiderData(HttpServletRequest req, HttpServletResponse resp){
        String keyword = RequestUtil.getStrParameter(req, "keyword");
        String spiderTaskId = RequestUtil.getStrParameter(req, "spiderTaskId");
        if(validParam(req, resp, new Object[]{keyword, spiderTaskId}, new String[]{"关键字", "参数spiderTaskId"})){
            List<Map<String, String>>  list =  SpiderService.pageCrawl(spiderTaskId, keyword);
            PageJumpUtil.writeObjToJson(list, resp);
        }
    }

    @ReqMapping(desc = "采用爬虫数据", method = ReqMethod.POST)
    private void adoptQASpiderData(HttpServletRequest req, HttpServletResponse resp){
        Integer index = RequestUtil.getIntParameter(req, "index");
        String categoryId = RequestUtil.getStrParameter(req, "firstCategoryId");
        String taskId = RequestUtil.getStrParameter(req, "taskId");
        if(validParam(req, resp, new Object[]{index, categoryId, taskId}, new String[]{"参数index", "参数firstCategoryId", "参数taskId"})){
            indexApi.addQAData(taskId, categoryId, index);
            PageJumpUtil.writeJsonOk("数据已成功加入系统问题库", resp);
        }
    }

}
